<template>
  <div class="shopping">
    <van-nav-bar title="购物车">
      <template #right>
        <div @click="toggleEditStatus">{{ !isEdit ? "编辑" : "完成" }}</div>
      </template>
    </van-nav-bar>
    <div class="bg-img"><img src="../assets/img/bg1.jpeg" alt="" /></div>
    <div style="padding: 0 10px 110px 10px">
      <van-swipe-cell
        :disabled="isEdit"
        v-for="(item, index) in shopbagAllData"
        :key="item.sid"
      >
        <div class="da-box">
          <div class="por-box">
            <div class="por-bon">
              <van-checkbox
                v-model="item.isChecked"
                icon-size="20px"
                @change="simpleSelect"
              ></van-checkbox>
            </div>
            <div class="por-img">
              <img class="auto-img" :src="item.small_img" alt />
            </div>
            <div class="por-text">
              <div class="text-name">
                <div class="name">{{ item.name }}</div>
                <div class="tang">{{ item.rule }}</div>
              </div>
              <div class="text-enname">{{ item.enname }}</div>
              <div class="pro-price">
                <div class="price">￥{{ item.price }}</div>
                <van-stepper
                  v-model="item.count"
                  theme="round"
                  button-size="22"
                  disable-input
                  @change="updateShopbagCount(item.sid, item.count)"
                />
              </div>
            </div>
          </div>
        </div>
        <template #right>
          <van-button
            square
            type="danger"
            @click="removeShopbag([item.sid], index)"
            text="删除"
          />
        </template>
      </van-swipe-cell>
    </div>
    <van-submit-bar
      v-show="!isEdit"
      :price="total"
      button-text="提交订单"
      button-color="#05a1f4"
      @submit="commit"
    >
      <van-checkbox v-model="checked" @click="allSelect">全选</van-checkbox>
    </van-submit-bar>

    <van-submit-bar
      v-show="isEdit"
      button-text="删除选择"
      button-color="#05a1f4"
      @submit="removeSelect"
    >
      <van-checkbox v-model="checked" @click="allSelect">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import "../assets/less/shopping.less";

import { mapState, mapMutations } from "vuex";
export default {
  name: "Shopping",
  data() {
    return {
      //是否编辑商品
      isEdit: false,

      //购物袋所有数据
      shopbagAllData: [],

      //全选或者取消全选
      checked: false,

      //总金额
      total: 0,
    };
  },
  computed: {
    ...mapState(["shopbagCount"]),
  },
  created() {
    this.getShopbagData();
  },
  methods: {
    ...mapMutations(["changeShopbagCount"]),
    //返回上一级
    back() {
      this.$router.go(-1);
    },
    //切换编辑状态
    toggleEditStatus() {
      this.isEdit = !this.isEdit;
    },
    //获取购物袋数据
    getShopbagData() {
      let tokenString = this.$cookies.get("tokenString");
      // console.log("tokenString ==> ", tokenString);

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "GET",
        url: this.baseUrl + "/findAllShopcart",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((res) => {
          // console.log("res getLikeProduct ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            return this.$router.push({ name: "Login" }); //跳转到登录
          }

          if (res.data.code === 5000) {
            res.data.result.forEach((v) => {
              v.isChecked = false; //添加复选框状态
            });
            //购物袋所有数据
            this.shopbagAllData = res.data.result;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    //修改购物袋数量
    updateShopbagCount(sid, count) {
      let tokenString = this.$cookies.get("tokenString");
      // console.log("tokenString ==> ", tokenString);

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "POST",
        url: this.baseUrl + "/modifyShopcartCount",
        data: {
          appkey: this.appkey,
          tokenString,
          sid,
          count,
        },
      })
        .then((res) => {
          // console.log("res updateShopbagCount ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code !== 6000) {
            this.sum();
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
          }
          this.sum();
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    //全选
    allSelect() {
      //将所有单选状态修改位全选状态
      this.shopbagAllData.forEach((v) => {
        v.isChecked = this.checked;
      });
      this.sum();
    },
    //单选
    simpleSelect() {
      this.sum();
      //只要有一个单选没有勾选，则全选不能勾选
      for (let i = 0; i < this.shopbagAllData.length; i++) {
        if (!this.shopbagAllData[i].isChecked) {
          this.checked = false;
          return;
        }
      }
      if (this.shopbagAllData.length > 0) {
        this.checked = true;
      }
    },
    //删除购物袋数据, 删除成功后, 记得修改vuex的购物袋数量
    removeShopbag(sids, index) {
      let tokenString = this.$cookies.get("tokenString");
      // console.log("tokenString ==> ", tokenString);

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.axios({
        method: "POST",
        url: this.baseUrl + "/deleteShopcart",
        data: {
          appkey: this.appkey,
          tokenString,
          sids: JSON.stringify(sids),
        },
      })
        .then((res) => {
          console.log("res getShopbagData ==>", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code == 7000) {
            //如果是单个
            if (index !== undefined) {
              this.shopbagAllData.splice(index, 1);

              this.changeShopbagCount(this.shopbagCount - 1);

              this.simpleSelect();
            } else {
              //执行多个删除
              for (let i = 0; i < this.shopbagAllData.length; i++) {
                if (this.shopbagAllData[i].isChecked) {
                  this.shopbagAllData.splice(i, 1);
                  i--;
                }
              }
              this.changeShopbagCount(this.shopbagCount - sids.length);
              this.sum();
            }
          }
          this.$toast({
            message: res.data.msg,
            forbidClick: true,
            duration: 1000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    //删除选择的购物袋商品
    removeSelect() {
      //获取勾选的sid
      let sids = [];
      this.shopbagAllData.forEach((v) => {
        if (v.isChecked) {
          sids.push(v.sid);
        }
      });
      if (sids.length === 0) {
        this.$toast({
          message: "未选择删除商品",
          forbidClick: true,
          duration: 3000,
        });
        return;
      }
      console.log("sids ==> ", sids);

      this.removeShopbag(sids);
    },
    //计算勾选的商品总金额
    sum() {
      let total = 0;
      this.shopbagAllData.forEach((v) => {
        if (v.isChecked) {
          total += v.price * v.count;
        }
      });
      this.total = total * 100;
    },
    //提交订单
    commit() {
      //获取勾选的sid
      let sids = [];
      this.shopbagAllData.forEach((v) => {
        if (v.isChecked) {
          sids.push(v.sid);
        }
      });

      if (sids.length === 0) {
        this.$toast({
          message: "选择下单的商品",
          forbidClick: true,
          duration: 3000,
        });

        return;
      }
      console.log(sids)
      this.$router.push({ name: "Pay", query: { sids: sids.join("-") } });
    },
  },
};
</script>

<style lang="less" scoped>
</style>